
// DifferFinderDlg.cpp : implementation file
//

#include "stdafx.h"
#include "DifferFinder.h"
#include "DifferFinderDlg.h"
#include <util.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#define MAX_DIS 256

// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CDifferFinderDlg dialog




CDifferFinderDlg::CDifferFinderDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CDifferFinderDlg::IDD, pParent)
	, m_strTargetKey(_T(""))
	, m_strPath(_T(""))
	, m_nResult(0)
	, m_nRange(0)
	, m_nTotalNumber(0)
	, m_strState(_T("Ready"))
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CDifferFinderDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT1, m_strTargetKey);
	DDX_Text(pDX, IDC_EDIT2, m_strPath);
	DDX_Text(pDX, IDC_EDIT4, m_nResult);
	DDX_Text(pDX, IDC_EDIT3, m_nRange);
	DDX_Text(pDX, IDC_EDIT5, m_nTotalNumber);
	DDX_Text(pDX, IDC_EDIT6, m_strState);
}

BEGIN_MESSAGE_MAP(CDifferFinderDlg, CDialog)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BUTTON_CALCULATE_RATE, &CDifferFinderDlg::OnBnClickedButtonCalculate)
	ON_BN_CLICKED(IDC_BUTTON_BROWSE, &CDifferFinderDlg::OnBnClickedButtonBrowse)
	ON_WM_TIMER()
	ON_EN_CHANGE(IDC_EDIT6, &CDifferFinderDlg::OnEnChangeEdit6)
	ON_BN_CLICKED(IDC_BUTTON_DRAW_DISTRIBUTION, &CDifferFinderDlg::OnBnClickedButtonDrawDistribution)
END_MESSAGE_MAP()


// CDifferFinderDlg message handlers

BOOL CDifferFinderDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CDifferFinderDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CDifferFinderDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CDifferFinderDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CDifferFinderDlg::OnBnClickedButtonCalculate()
{
	this->UpdateData(TRUE);
	ofstream fout("buffer.tmp");
	if(fout.is_open()==true)
	{
		fout<<this->m_strTargetKey.GetBuffer()<<endl;
		fout.close();
		ifstream fin("buffer.tmp");
		if(fin.is_open()==true)
		{
			fin>>this->m_cTargetId;
			if(fin.fail())
			{
				MessageBox("Target Key ERROR","ERROR",MB_OK|MB_ICONERROR);
				return ;
			}
			else
			{
				ifstream fin(this->m_strPath.GetBuffer());
				if(fin.is_open()==true)	
				{
					CID cId;
					this->m_nTotalNumber = 0;
					this->m_nResult=0;
					while(fin>>cId)
					{
						if(GetDistance(cId,m_cTargetId)<=this->m_nRange)
						{
							m_nResult++;
						}
						m_nTotalNumber++;
					}
					this->SetState("Finish!");
					this->m_strTargetKey="";
					this->UpdateData(FALSE);
				}
				else
				{
					MessageBox("Key FILE path error","ERROR",MB_OK|MB_ICONERROR);
					return ;
				}
			}
		}
		else
		{
			MessageBox("ERROR OPEN FILE","ERROR",MB_OK|MB_ICONERROR);
			return ;
		}
	}
	else
	{
		MessageBox("ERROR CREATE FILE","ERROR",MB_OK|MB_ICONERROR);
		return ;
	}
	// TODO: Add your control notification handler code here
}

void CDifferFinderDlg::OnBnClickedButtonBrowse()
{
	this->UpdateData();
	CFileDialog cPathDiag(TRUE,NULL,NULL,6,"Nilsimsa Key Files (*.nil)|*.nil||");
	if(cPathDiag.DoModal()==IDOK)
	{
		this->m_strPath = cPathDiag.GetPathName ();
		this->UpdateData(FALSE);
	}
}

void CDifferFinderDlg::SetState(CString  strState,int nLastSecond)
{
	this->m_strState=strState;
	this->UpdateData(FALSE);
	this->SetTimer(123,nLastSecond*1000,NULL);
}

void CDifferFinderDlg::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: Add your message handler code here and/or call default
	this->m_strState="Ready";
	this->UpdateData(FALSE);
	CDialog::OnTimer(nIDEvent);
	this->KillTimer(123);
}

void CDifferFinderDlg::OnEnChangeEdit6()
{
	// TODO:  If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.

	// TODO:  Add your control notification handler code here
}

void CDifferFinderDlg::OnBnClickedButtonDrawDistribution()
{
	// TODO: Add your control notification handler code here
	CCalculator cCal;
	int nTimes = 10000;
	this->UpdateData();
	ifstream fin(this->m_strPath.GetBuffer());
	vector<CID> cList;
	if(fin.is_open()==true)	
	{
		CID cId;
		while(fin>>cId)
		{
			for(unsigned i =0;i<cList.size();i++)
			{
				if(nTimes--<0)
				{
					break;
				}
				cCal.Add(GetDistance(cId,cList[i]));
			}
			cList.push_back(cId);
		}
		cCal.Calculate();
	}
	vector<pair<double ,double>> cPdf,cCdf;
	cCal.GetPDF(60,0,256,cPdf);
	cCal.GetCDF(60,0,256,cCdf);
	CString strName("DataDistribution_of_");
	strName.Append("Nilsimsa");
	CFileDialog cFile(FALSE,"eps",strName,6,"EPS Files (*.eps)|*.eps||");
	if(cFile.DoModal()==IDOK)
	{
		CString strFigureNamePath(cFile.GetPathName());
		CString strRawDataNamePath(strFigureNamePath);
		strRawDataNamePath=strRawDataNamePath.Left(strRawDataNamePath.ReverseFind('.'));
		strRawDataNamePath.Append(".dat");
		CString strScriptNamePath(strFigureNamePath.Left(strFigureNamePath.ReverseFind('.')));
		strScriptNamePath.Append(".plt");
		ofstream fout(strRawDataNamePath.GetString());
		if(fout)
		{
			for (unsigned i = 0;i<cPdf.size();i++)
			{
				fout<<cPdf[i].first<<" "<<cPdf[i].second<<" "<<cCdf[i].first<<" "<<cCdf[i].second<<endl;	
			}
			fout.close();
		}
		else
		{
			this->MessageBox("Create Data File Error!");
			return ;
		}
		CString strXCoordinate;
		strXCoordinate.Format("0,%u,%u,%u,%u,%u,%u,%u,%u",MAX_DIS/8*1,MAX_DIS/8*2,MAX_DIS/8*3,MAX_DIS/8*4,MAX_DIS/8*5,MAX_DIS/8*6,MAX_DIS/8*7,MAX_DIS );
		CString script("reset \n");
		script.AppendFormat("set term postscript eps color enhanced \n");
		script.AppendFormat("set output '%s'\n",strFigureNamePath.GetString());
		script.AppendFormat("unset key \n");
		script.AppendFormat("set multiplot\n");
		script.AppendFormat("set size 0.4,0.6\n");
		script.AppendFormat("set origin 0.1,0.1\n");
		script.AppendFormat("set title '(a) PDF'\n");
		script.AppendFormat("set xlabel 'Distance'\n");
		script.AppendFormat("set xtics (%s) \n",strXCoordinate.GetString());
		script.AppendFormat("plot '%s' using 1:2   with l lt 1 lw 2 \n",strRawDataNamePath.GetString());
		
		script.AppendFormat("set size 0.4,0.6\n");
		script.AppendFormat("set origin 0.5,0.1\n");
		script.AppendFormat("set title '(b) CDF'\n");
		script.AppendFormat("set xlabel 'Distance'\n");
		script.AppendFormat("set xtics (%s) \n",strXCoordinate.GetString());
		script.AppendFormat("plot '%s' using 3:4   with l lt 1 lw 2 \n",strRawDataNamePath.GetString());
		script.AppendFormat("unset multiplot\n");
		script.AppendFormat("reset \n");
		script.AppendFormat("set term windows\n");
		script.AppendFormat("unset key \n");
		script.AppendFormat("set multiplot\n");
		script.AppendFormat("set size 0.4,0.6\n");
		script.AppendFormat("set origin 0.1,0.1\n");
		script.AppendFormat("set title '(a) PDF'\n");
		script.AppendFormat("set xlabel 'Distance'\n");
		script.AppendFormat("set xtics (%s) \n",strXCoordinate.GetString());
		script.AppendFormat("plot '%s' using 1:2   with l lt 1 lw 2 \n",strRawDataNamePath.GetString());
		
		script.AppendFormat("set size 0.4,0.6\n");
		script.AppendFormat("set origin 0.45,0.1\n");
		script.AppendFormat("set title '(b) CDF'\n");
		script.AppendFormat("set xlabel 'Distance'\n");
		script.AppendFormat("set xtics (%s) \n",strXCoordinate.GetString());
		script.AppendFormat("plot '%s' using 3:4   with l lt 1 lw 2 \n",strRawDataNamePath.GetString());
		script.AppendFormat("unset multiplot\n");
		FILE *pFile ;
		if(0==fopen_s(&pFile,strScriptNamePath.GetString(),"w"))
		{
			fwrite(script.GetBuffer(),1,script.GetLength(),pFile);
			fclose(pFile);
			CString cmd;
			cmd.Format("pgnuplot.exe -persist \"%s\"",strScriptNamePath.GetString());
			WinExec(cmd.GetString(),SW_SHOW);
		}
		else
		{
			MessageBox("Open File Error!");
			return ;
		}
	}
}
